package com.miaoshaconsumer.service;

import com.miaoshaconsumer.pojo.Product;
import com.miaoshaconsumer.pojo.Productrecord;
import jakarta.annotation.Resource;
import com.miaoshaconsumer.mapper.ProductMapper;
import com.miaoshaconsumer.mapper.ProductRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "MiaoShaQueue")
public class DirectReceiver {
	private static final Logger LOGGER= LoggerFactory.getLogger(DirectReceiver.class);
	@Resource
	ProductMapper productMapper;
	@Resource
	ProductRecordMapper productRecordMapper;
	@RabbitHandler(isDefault = true)
	void process(Map<String,Object> message) {
		System.out.println("消费者DirectReceiver收到消息  : "+ message.get("messageData"));
		Integer userId = Integer.parseInt(message.get("messageData").toString());
		Product product=productMapper.findByProductNo(101);
		if (product != null&&product.getTotal()>0) {
			product.setTotal(product.getTotal()-1);
			int i = productMapper.updateById(product);
			if (i>0) {
				productRecordMapper.insert(new Productrecord(101,userId));
				LOGGER.info("用户{}抢单成功",userId);
			}else {
				LOGGER.info("用户{}抢单失败",userId);
			}
		}else {
			LOGGER.info("用户{}抢单失败",userId);
		}
	}
}
